import cors from 'cors';
import express from 'express';
import proxy from 'express-http-proxy';
import {RequestHandler} from 'next/dist/server/next';
import * as trpcExpress from '@trpc/server/adapters/express';
import {
    BUILD_ASSETS_PATH, DEV_NEXT_URL, PUBLIC_ASSETS_PATH,
    SERVER_PORT, SERVER_TRPC_PREFIX, SERVER_URL, STATIC_PREFIX
} from '@/config/dev';
import {appRouter} from '@/server/trpc';
import {CatchAsyncError, CatchSyncError} from './middlewares/catch-error';
import {apiRouter} from './routers';


// const prod = process.env.NODE_ENV === 'production';
// const cwd = process.cwd();

export const createServer = (options?: { nextHandler?: RequestHandler }) => {
    const {nextHandler} = options || {};
    const server = express();

    server.use(CatchAsyncError());
    // 静态资源
    server.use(express.static(PUBLIC_ASSETS_PATH));
    server.use(STATIC_PREFIX, express.static(BUILD_ASSETS_PATH));
    // 跨域
    server.use(cors());
    // trpc
    server.use(SERVER_TRPC_PREFIX, trpcExpress.createExpressMiddleware({
        router: appRouter,
        createContext: ({req, res}: trpcExpress.CreateExpressContextOptions) => ({})
    }));
    // 解析body、api
    server.use('/api', express.json(), apiRouter);
    server.use(CatchSyncError());
    // next view
    server.use('*', nextHandler ? (req, res) => nextHandler(req, res) : proxy(DEV_NEXT_URL));

    server.listen(SERVER_PORT, () => {
        console.log(`> Ready on ${SERVER_URL}`);
    });
};
